package com.le.tester.tip;

import java.util.concurrent.CountDownLatch;

/**
 * createTime：2022/2/9 16:32
 * description：使用countDownLatch中的倒计时来规定执行的顺序
 */
public class MultiThreadOrderExecWithCountDown {

    public static void main(String[] args) {
        //计数器为0
        CountDownLatch c1 = new CountDownLatch(0);
        //计数器为1
        CountDownLatch c2 = new CountDownLatch(1);
        //计数器为2,没法置成0,导致整个程序卡死
        CountDownLatch c3 = new CountDownLatch(1);

        Thread t1 = new Thread(new Work(c1, c2), "线程1");
        Thread t2 = new Thread(new Work(c2, c3), "线程2");
        Thread t3 = new Thread(new Work(c3, c3), "线程3");


        t1.start();
        t2.start();
        t3.start();
    }

    static class Work implements Runnable {

        private CountDownLatch c1;
        private CountDownLatch c2;

        //只是用构造器进行了初始化而已
        public Work(CountDownLatch c1, CountDownLatch c2) {
            super();
            this.c1 = c1;
            this.c2 = c2;
        }

        @Override
        public void run() {
            try {
                //调用了wait之后，只有在计数器变成0之后，才会执行
                c1.await();
                System.out.println("Thread start:" + Thread.currentThread().getName());
                c2.countDown();
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            }
        }
    }
}
